/*
 * @Date: 2021-02-02 15:54:05
 * @LastEditors: E'vils
 * @LastEditTime: 2021-04-29 16:33:12
 * @Description: 
 * @FilePath: /src/pages/tablePreview/tablePreview.js
 */
/* eslint-disable no-undef */
//index.js
//获取应用实例
const app = getApp();


import dayjs from "../../utils/dayjs.min";
import {
  get_qinglv,
  get_show,
  get_kebiao,
  unbind_qinglv
} from "../../api/shool/get_score.js";

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';


Page({
  data: {
    is_qie: true,
    if_love: wx.getStorageSync('user').birthday ? true : false,
    if_gd: false,
    bg_url: '',
    type_1: null,
    ke: false,
    value: null,
    xq: [{
        xn: '2019-2020',
        xq: [{
            type: '第一学期',
            id: 162
          },
          {
            type: '第二学期',
            id: 182
          },
        ],

      },
      {
        xn: '2020-2021',
        xq: [{
            type: '第一学期',
            id: 202
          },
          {
            type: '第二学期',
            id: 222
          },
        ],

      },
      {
        xn: '2021-2022',
        xq: [{
            type: '第一学期',
            id: 223
          },
          {
            type: '第二学期',
            id: 242
          },
        ],

      },
      {
        xn: '2022-2023',
        xq: [{
            type: '第一学期',
            id: 262
          },
          {
            type: '第二学期',
            id: 262
          },
        ],

      },
    ],
    time_list: null,
    ke_list: [],
    xq_type: [
      "上学年",
      "下学年"
    ],

    xq_id: 242,
    xq_value: '2022-2023',
    xq_type_1: '第1学期',

    show_1: false,
    show: false,
    showWeek: 1,
    nowM: 5,
    time: '',
    list: [],
    ke_lis: [],
    nowW: 1,
    nowW_1: 1,
    colorArrays: ["#FC5C7D", "#52DB9A", "#4ADBC3", "#6A82FB", "#673AB7", "#48A8E4", "#70D3E6", "#F3D147", "#04E300"],
    wlist: [],
    week: [],
  },
  //切换情侣课表
  change_kebiao(e) {
    wx.vibrateShort({
      type: 'heavy',
      success: res => {
        console.log(res)
      }
    })
    this.data.is_qie = !this.data.is_qie;
    this.refresh()

    this.setData({
      is_qie: this.data.is_qie
    })
  },
  //解除关联
  lout_love() {
    Dialog.confirm({
        title: '解除绑定',
        message: '您确定要解除情侣课表的绑定吗？',
      })
      .then(() => {
        unbind_qinglv().then(res => {
          if (res.statusCode == 200) {
            //提示用户解除绑定成功
            wx.showToast({
              title: '解绑成功',
              icon: 'none',
              duration: 1000
            })
            //清除缓存
            wx.removeStorageSync('ke_list_love'),
              wx.removeStorageSync('dayke_list_love'),
              wx.removeStorageSync('ke_time_love')

            //修改缓存user用户信息
            let user = wx.getStorageSync('user')
            user.birthday = '',
              //存入缓存
              wx.setStorageSync('user', user)

            this.setData({
              if_love: false,
              is_qie: true,
            })

          }

        })
      })
  },

  //点击更多
  genduo() {
    this.setData({
      if_gd: !this.data.if_gd
    })

  },
  //点击查看课程详情
  showCardView(e) {
    console.log(e)
    this.setData({
      ke: true,
      value: e.currentTarget.dataset.value
    })
  },

  //获取图片
  afterRead(e) {
    console.log(e.detail)
    wx.setStorageSync('bg_url', e.detail.file.url)
    this.setData({
      bg_url: e.detail.file.url
    })
  },
  //删除背景
  del_bg() {
    wx.removeStorageSync('bg_url')
    this.setData({
      bg_url: ''
    })
  },
  //刷新课表
  refresh() {
    wx.vibrateShort({
      type: 'heavy',
      success: res => {
        console.log(res)
      }
    })
    wx.removeStorageSync('ke_list')
    this.setData({
      wlist: [],
      week: [],
    })

    this.onLoad()
  },


  //选择学期
  bindChange(e) {
    const val = e.detail.value
    console.log(this.data.xq[val[0]].xq[val[1]].id)
    if (this.data.is_qie) {
      this.get_kebiao(this.data.xq[val[0]].xq[val[1]].id)
    } else {
      this.get_qinglv(this.data.xq[val[0]].xq[val[1]].id)
    }


    this.setData({
      xq_value: this.data.xq[val[0]].xn,
      xq_type_1: this.data.xq[val[0]].xq[val[1]].type
    })

  },
  //打开选择学期事件
  shan_xq() {
    this.setData({
      show_1: !this.data.show_1,
      if_gd: false
    })
  },
  showPopup() {
    this.setData({
      show: !this.data.show
    });
  },
  //关闭下拉
  onClose() {
    this.setData({
      show: false
    });
  },
  close_xl() {
    console.log('1')
    this.setData({
      show: false
    });
  },
  //生成一周日期列表
  getWeekList: function () {
    let now = new Date();
    let nowM = now.getMonth() + 1;
    let nowD = now.getDate();
    let nowY = now.getFullYear();
    let nowH = now.getHours();
    let nowMi = now.getMinutes();
    let nowS = now.getSeconds();
    let nowTime = nowY + "-" + nowM + "-" + nowD + " " + nowH + ":" + nowMi + ":" + nowS;
    this.data.time = dayjs(nowTime).format("MM/DD");
    let now_1 = dayjs(nowTime).format("YYYY-MM-DD");
    let end_1 = wx.getStorageSync('userinfo').options.start_time||'2022-08-29'
    this.data.nowW = parseInt(this.DateDiff(end_1, now_1) / 7 + 1)
    this.data.nowM = dayjs(nowTime).format("M");
    this.data.nowW_1 = this.data.nowW
    //生成一周日期列表
    this.GetMonday()
    this.setData({
      nowM: this.data.nowM,
      nowW: this.data.nowW,
      nowW_1: this.data.nowW,
      time: this.data.time,
    })

  },
  //生成一周列表
  GetMonday() {
    let h = this.data.nowW-this.data.nowW_1   - 1
    console.log(h);
    // let h = 3
    let weekList = [];
    let arr = ['一', '二', '三', '四', '五', '六', '日']
    let dd = new Date();
    var week = dd.getDay(); //获取时间的星期数
    console.log(week);
    var minus =  week + 6 + 7 * h ;
    dd.setDate(dd.getDate() - minus); //获取minus天前的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取月份
    var d = dd.getDate();
    let nowH = dd.getHours();
    let nowMi = dd.getMinutes();
    let nowS = dd.getSeconds();
    //切换周数
    let nowTime = y + "-" + m + "-" + d + " " + nowH + ":" + nowMi + ":" + nowS
    console.log(nowTime);
    for (let i = 0; i < 7; i++) {
      let time = dayjs(nowTime).add(i, 'day').format("MM/DD");
      console.log(time);
      weekList.push({
        week_name: arr[i],
        week_time: time,
      });
    }
    this.data.week = weekList
    this.setData({
      week: weekList,
      nowM: m,
    })



    // return;
  },
  //请求课表
  get_kebiao(id) {
    get_kebiao({
      semesterId: id,
      week: 1
    }).then(res => {
      if (res.data.statusCode == 200) {
        this.data.list = res.data.data.value,
          this.data.xq = res.data.data.xq //学年选项
        this.data.start_time = res.data.data.start_time //起始时间
        //去掉重复的课程
        this.data.list = this.deteleObject(this.data.list)
        this.data.ke_list = res.data.data.ke

        this.data.time_list = res.data.data.time_list

        wx.setStorageSync('ke_time', res.data.data.time_list)
        
        this.setData({
          time_list: res.data.data.time_list

        })

        this.show_kebiao(this.data.list, this.data.ke_list)
      } else {
        Toast('获取课表失败');
      }

    })
  },
  //请求情侣课表
  get_qinglv(id) {
    console.log(id)
    get_qinglv(id).then(res => {
      this.data.list = res.data.data.value,

        //去掉重复的课程
        this.data.list = this.deteleObject(this.data.list)
      this.data.ke_list = res.data.data.ke

      this.data.time_list = res.data.data.time_list

      wx.setStorageSync('ke_time', res.data.data.time_list)
      this.setData({
        time_list: res.data.data.time_list

      })

      this.show_kebiao(this.data.list, this.data.ke_list)
    })
  },

  //去掉相同对象
  deteleObject(obj) {
    var uniques = [];
    var stringify = {};
    for (var i = 0; i < obj.length; i++) {
      var keys = Object.keys(obj[i]);
      keys.sort(function (a, b) {
        return (Number(a) - Number(b));
      });
      var str = '';
      for (var j = 0; j < keys.length; j++) {
        str += JSON.stringify(keys[j]);
        str += JSON.stringify(obj[i][keys[j]]);
      }
      if (!stringify.hasOwnProperty(str)) {
        uniques.push(obj[i]);
        stringify[str] = true;
      }
    }
    uniques = uniques;
    return uniques;
  },
  //渲染课表
  show_kebiao(arr, ke) {
    //初始化课表数据
    this.data.wlist = []
    for (var i = 0; i < arr.length; i++) {
      for (var j = 0; j < arr[i].value.pai6.length; j += 2) {
        var y2 = parseInt(arr[i].value.pai6[j][0].split("=")[1]);
        var x2 = parseInt(arr[i].value.pai6[j + 1][0].split("+")[1]);
        var name = arr[i].value.name.replace(/\\"|\"/g, "");
        var id = arr[i].value.id.replace(/\\"|\"/g, "");
        var room = arr[i].value.room.replace(/\\"|\"/g, "");
        var week = arr[i].value.week.replace(/\\"|\"/g, "");
        //          * 对教学周占用串进行缩略表示 marsh a string contain only '0' or '1' which named
        //  * "vaildWeeks" with length 53
        //  * 00000000000000000100000000000000000000000000000000000|
        //缩略连续周
        var vaildWeeks = [];
        for (var k = 0; k < week.length; k++) {
          if (week[k] == "1") {
            vaildWeeks.push(k);
          }
        }

        //辨别当前周
        var teacher1 = null;
        for (let j = 0; j < ke.length; j++) {
          if (ke[j].name == name) {
            teacher1 = ke[j].teacher;
          }
        }

        for (let i = 0; i < vaildWeeks.length; i++) {
          if (vaildWeeks[i] == this.data.nowW_1) {
            if (teacher1 == null) teacher1 = "未知";

            this.data.wlist.push({
              "xqj": y2 + 1,
              "skjc": x2 + 1,
              "skcd": 1,
              "kcmc": name,
              "room": room,
              "tea": teacher1,


            })


            //   this.timetables[y2][x2] =
            //     name + "(" + teacher1 + "）\n " + id + " \n" + room;

          }
        }

        //合并相同课程

        for (let i = 0; i < this.data.wlist.length - 1; i++) {
          if (this.data.wlist[i].kcmc == this.data.wlist[i + 1].kcmc && this.data.wlist[i].xqj == this.data.wlist[i + 1].xqj && this.data.wlist[i].room == this.data.wlist[i + 1].room&&this.data.wlist[i].skjc+1 == this.data.wlist[i + 1].skjc) {
            this.data.wlist[i].skcd += this.data.wlist[i + 1].skcd
            this.data.wlist.splice(i + 1, 1)

          }
          this.data.wlist[i].jie = this.look_ke(this.data.wlist[i].xqj, this.data.wlist[i].skjc, this.data.wlist[i].skcd)
        }
console.log(this.data.wlist);

        this.setData({
          wlist: this.data.wlist
        })
      }



    }


    if (this.data.id = 242) {
      wx.setStorageSync('kebiao_list', this.data.wlist)
    }
    // this.get_dayke()
  },
  //读取课表
  look_ke(xqj, jie, skcd) {
    let arr = ['一', '二', '三', '四', '五', '六', '日']
    //计算节数

    return {
      "xqj": `星期${arr[xqj-1]}`,
      "skjc": `第${jie}~${jie-1+skcd}节`,
    }
  },
  //获取当天课表
  // get_dayke() {
  //     let index = 0;
  //     for (let i = 0; i < this.data.week.length; i++) {
  //         if (this.data.time == this.data.week[i].week_time) {
  //             index = i+1
  //         }
  //     }
  //       
  //  //筛选当日课程
  //  const day_arr=this.data.wlist.filter(item=>{
  //      if(index==item.xqj){
  //          item.time=`${this.data.time_list[item.skjc-1]}~${this.data.time_list[item.skjc+item.skcd-2]}`;
  //          item.type= this.Remind(item.time)
  //          return item
  //      }
  //  })
  //  //存入缓存
  //  wx.setStorageSync('dayke_list', day_arr)
  // },
  // checkdate(t1, t2) {
  //     let t11 = t1.split(":");
  //     let t21 = t2.split(":");
  //     let sj1 = parseInt(t11[0] * 12 + t11[1]);
  //     let sj2 = parseInt(t21[0] * 12 + t21[1]);
  //     return sj1 > sj2 ? false : true;
  // },
  // Remind(data) {
  //     let t11 = data.split("~");
  //     let now = dayjs().format("HH:mm");
  //     let tipEvent = dayjs().subtract(30, "minute").format("HH:mm");
  //     let stime = t11[0];
  //     let etime = t11[1];
  //     if (this.checkdate(etime, now)) {
  //         return 3; // 已结束
  //     } else if (this.checkdate(stime, now)) {
  //         return 2; // 进行中
  //     } else if (!this.checkdate(stime, tipEvent)) {
  //         return 1; // 即将开始
  //     } else {
  //         return 0; //不显示
  //     }
  // },

  //计算当前周
  DateDiff(sDate1, sDate2) {
    var oDate1, oDate2, iDays
    oDate1 = new Date(sDate1).getTime()
    oDate2 = new Date(sDate2).getTime()
    iDays = parseInt((oDate2 - oDate1) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数   
    return iDays
  },

  onClose() {
    this.setData({
      show_1: false
    });
  },
  channowW() {
    this.setData({
      nowW_1: this.data.nowW,
    })
    this.GetMonday()
    this.show_kebiao(this.data.list, this.data.ke_list)
  },
  chanWeek(e) {
    this.data.nowW_1 = e.currentTarget.dataset.week
    this.setData({
      nowW_1: this.data.nowW_1,
      show: false,
    })
    this.GetMonday()
    this.show_kebiao(this.data.list, this.data.ke_list)

  },
  async onLoad() {
    this.setData({
      is_six: wx.getStorageSync('userinfo').sex.value
    })
    this.data.xq_id= wx.getStorageSync('userinfo').options.xq
    this.getWeekList()
    if (wx.getStorageSync('ke_list')) {
      let value = null
      if (this.data.is_qie) {
        value = wx.getStorageSync('ke_list')
      } else {
        value = wx.getStorageSync('ke_list_love')
      }

      this.data.list = value.ke
      this.data.ke_list = value.list
      this.data.time_list = wx.getStorageSync('ke_time')
      this.setData({
        time_list: wx.getStorageSync('ke_time'),
      })
      this.show_kebiao(value.ke, value.list)
    } else {
      if (this.data.is_qie) {
        this.get_kebiao(this.data.xq_id)
      } else {
        this.get_qinglv(this.data.xq_id)
      }

    }


    await get_show().then(res => {

      if (res.data.password == app.getVersion()) {
        this.data.type_1 = res.data.stuNumber

      } else {
        this.data.type_1 = 'false'
      }
    })
    this.setData({
      type_1: this.data.type_1
    })
    let day = '2022-02-28'
    let nowM = dayjs().format("YYYY-MM-DD"); // 获取现在的月份
    let days = this.DateDiff(day, nowM) / 7
    this.setData({
      showWeek: parseInt(days + 1)
    });
  },
  onShow: function () {
    console.log( wx.getStorageSync('xq'));
    try {
      this.data.bg_url = wx.getStorageSync('bg_url')
      this.setData({
      xq: wx.getStorageSync('xq'),
      if_love: wx.getStorageSync('user').birthday ? true : false,
      bg_url: this.data.bg_url
    })
    } catch (error) {
      
    }
    

  },

});